package articles_api

import (
	"context"
	"fmt"
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"gin_study_blog/utils"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic/v7"
)

type IDListRequest struct {
	IDList []string `json:"id_list"`
}

func (ArticlesApi) ArticleDeleteView(c *gin.Context) {
	var cr IDListRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		http.FailWithCode(http.ParamsError, c)
		return
	}

	// 如果文章删除了, 用户收藏了这篇文章怎么办?
	// 1. 删除文章时将与文章关联的收藏也删除了
	// 2. 用户收藏表, 新增一个字段, 是否被删除, 用户找不到文章去找收藏数
	bulkService := common.EsClient.Bulk().
		Index(models.ArticleModel{}.Index()).
		Refresh("true")
	for _, id := range cr.IDList {
		req := elastic.NewBulkDeleteRequest().Id(id)
		bulkService.Add(req)
		// 删除文章
		go utils.DeleteFullTextByArticleID(id)
	}
	res, err := bulkService.Do(context.Background())
	if err != nil {
		common.Log.Error(err)
		http.FailWithMessage("删除失败", c)
		return
	}
	http.IsOkWithMessage(fmt.Sprintf("成功删除 %d 文章", len(res.Succeeded())), c)
}
